package com.heima.wemedia.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.alibaba.fastjson.JSON;
import com.itheima.apis.schedule.IScheduleClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient iScheduleClient;


    @Autowired
    private WmNewsAutoScanService autoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Async
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        log.info("添加任务到延迟服务中----begin");

        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews newsTask = new WmNews();
        newsTask.setId(wmNews.getId());
        //调工具类 序列化传输对象
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        //添加任务
        iScheduleClient.addTask(task);
        log.info("添加任务到延迟服务中----end");

    }

    /**
     * 消费延迟队列数据
     */
    @Scheduled(fixedRate = 10000) //按固定频率每十秒拉取一次进行消费
    @Override
    public void scanNewsByTask() throws Exception {
        //通过feign接口拉取任务
        ResponseResult responseResult = iScheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        //判断是否拉取到任务
        if (null != responseResult && responseResult.getCode() == 200 && null != responseResult.getData() ) {

            //如果拉取到了任务就把任务中的参数取出来  获取到参数中的文字id 进行文字的审核操作
            String json = JSON.toJSONString(responseResult.getData());
            //把JSON转换为Task 获取到参数
            Task task = JSON.parseObject(json, Task.class);
            byte[] taskParameters = task.getParameters();
            //再反序列化将字节转化为 文章类型数据
            WmNews wmNews = ProtostuffUtil.deserialize(taskParameters, WmNews.class);
            //获取到延迟文章后再将文章发布
            autoScanService.autoScanWmNews(wmNews.getId());
        }
        log.info("文章审核---消费任务执行---end---");
    }
}
